from django.shortcuts import render

# Create your views here.

from rest_framework.viewsets import GenericViewSet, ViewSet
from rest_framework.mixins import DestroyModelMixin
from rest_framework.filters import SearchFilter
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Count

from charts.models import Host, Host_tags, Host_sources
from charts.serializer import HostModelSerializer, HostTagsModelSerializer, HostSourcesModelSerializer
from utils.Ops_mixins import OpsListModelMixin, OpsUpdateModelMixin, OpsDestroyModelMixin, OpsCreateModelMixin
from utils.Ops_page import HostPage
from utils.Ops_responses import OpsResponse
from libs.connect_influxdb.devops_influxdb import do_influx


class HostView(OpsListModelMixin, OpsDestroyModelMixin, OpsUpdateModelMixin, OpsCreateModelMixin, GenericViewSet):
    '''
    主机视图
    '''
    queryset = Host.objects.filter()
    serializer_class = HostModelSerializer

    pagination_class = HostPage
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = ['host_tag', 'host_source']
    search_fields = ['host_ip', 'host_name']


class HostTagsView(OpsListModelMixin, GenericViewSet):
    '''
    主机标签
    '''
    queryset = Host_tags.objects.filter()
    serializer_class = HostTagsModelSerializer


class HostSourcesView(OpsListModelMixin, GenericViewSet):
    '''
    主机来源
    '''
    queryset = Host_sources.objects.filter()
    serializer_class = HostSourcesModelSerializer


class HostTagSourcesNumView(ViewSet):
    @action(methods=['GET'], detail=False)
    def num(self, request):
        '''
        获取主机数量
        :param request:
        :return:
        '''
        tags = Host.objects.values('host_tag__tag').annotate(value=Count('id')).values('host_tag__tag', 'value')
        # tags = Host.objects.values('host_tag__tag').annotate(value=Count('id')).extra(select={'name': 'host_tag__tag'}).values('name', 'value')
        source = Host.objects.values('host_source__source').annotate(value=Count('id')).values('host_source__source', 'value')
        tag_lit = [{'name': i['host_tag__tag'], 'value': i['value']} for i in tags]
        source_lit = [{'name': i['host_source__source'], 'value': i['value']} for i in source]
        return OpsResponse(data={'tag': tag_lit, 'source': source_lit})

    @action(methods=['GET'], detail=False)
    def influx_info(self, request):
        client = do_influx()
        records = client.query("select * from test2_dev_ops where host_ip='c_centos1' and time > now() - 5m;")
        time_list = []
        ram_list = []
        for influx in records:
            for line in influx:
                time_list.append(line['time'].split('T'))
                ram_list.append(line['RAM'])
        return OpsResponse(time_list=time_list, ram_list=ram_list)

    @action(methods=['GET'], detail=False)
    def test(self, request):
        '''
        测试接口
        :param request:
        :return:
        '''
        host_all = Host.objects.filter(host_status=0, is_manage=0).values('host_ip', 'host_name')
        print(list(host_all))
        return OpsResponse(data={'host_all': host_all})

        # from libs.send_email.emails import s_mails
        # from libs.send_tx_sms.sms import send_sms_by_phone
        # 发送邮箱报警
        # alarm_name = 'wqeqe'
        # alarm_info = '34艾维奇二群二奥5'
        # s_mails.mails('发送邮件测试', f'{alarm_name}: {alarm_info}')
        # 使用腾讯云发送短信
        # send_sms_by_phone('123123', '17326040421')

